<template>
  <el-row>
    <el-col :span="5" style="height: 100%; padding-left: 20px; padding-top: 20px; border-right: 1px solid #dfe6ec">
      <div class="comp-tree">
        <el-button class="comp-tr-top" type="primary" size="small" @click="handleAddTop" style="width: auto">添加数据抽取任务目录</el-button>
        <!-- tree -->
        <el-tree
          ref="SlotTree"
          :data="treeList"
          :props="defaultProps"
          :current-node-key="currentNodekey"
          :expand-on-click-node="false"
          highlight-current
          :node-key="NODE_KEY"
          @node-click="handleNodeClick"
        >
          <div class="comp-tr-node" slot-scope="{ node, data }">
            <!-- 编辑状态 -->
            <template v-if="node.isEdit">
              <el-input v-model="data.name" autofocus size="mini" :ref="'slotTreeInput' + data[NODE_KEY]" @blur.stop="handleInput(node, data)" @keyup.enter.native="handleInput(node, data)"></el-input>
            </template>

            <!-- 非编辑状态 -->
            <template v-else>
              <!-- 名称： 新增节点增加class（is-new） -->
              <span :class="[data[NODE_KEY] < NODE_ID_START ? 'is-new' : '', 'comp-tr-node--name']">
                {{ node.label }}
              </span>

              <!-- 按钮 -->
              <span class="comp-tr-node--btns">
                <!-- 新增 -->
                <el-button icon="el-icon-plus" size="mini" circle type="primary" title="添加子节点" @click="handleAdd(node, data)"></el-button>
                <!-- 查看 -->
                <el-button icon="el-icon-document" size="mini" circle type="warning" title="查看节点详情" @click="handleLook(node, data)"></el-button>
                <!-- 编辑 -->
                <el-button icon="el-icon-edit" size="mini" circle type="info" title="编辑节点" @click="handleEdit(node, data)"></el-button>

                <!-- 删除 -->
                <el-button icon="el-icon-delete" size="mini" circle type="danger" title="删除节点" @click="handleDeletetree(node, data)"></el-button>
              </span>
            </template>
          </div>
        </el-tree>
      </div>
      <!-- </div>
    </div> -->
    </el-col>
    <el-col :span="18">
      <div class="app-container">
        <div class="filter-container">
          <div class="filter-item">
            <span class="span">目标模型编码/名称 </span>
            <el-input v-model="listQuery.name" placeholder="请输入目标模型编码/名称" style="width: 200px" />
          </div>
          <div class="filter-item">
            <span class="span">调度类型 </span>
            <el-select v-model="listQuery.dbType" clearable placeholder="调度类型" style="width: 200px">
              <el-option v-for="item in dictList('datasource_type')" :key="'type' + item.label" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="span">使用状态 </span>
            <el-select v-model="listQuery.status" clearable placeholder="请选择使用状态" style="width: 200px">
              <el-option v-for="item in dictList('is_use')" :key="'type' + item.label" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="span">执行状态 </span>
            <el-select v-model="listQuery.isSync" clearable placeholder="请选择执行状态" style="width: 200px">
              <el-option v-for="item in dictList('is_sync')" :key="'type' + item.label" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            {{ $t('table.search') }}
          </el-button>
          <!--          <el-button v-waves v-permission="['metadata:source:add']" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">-->
          <!--            {{ $t('table.add') }}-->
          <!--          </el-button>-->
          <!--          <el-button v-waves v-permission="['metadata:source:delete']" class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleBathDelete">-->
          <!--            {{ $t('table.delete') }}-->
          <!--          </el-button>-->
          <!--          <el-button v-waves v-permission="['metadata:source:import']" class="filter-item" type="primary" icon="el-icon-upload2" @click="handleImport">-->
          <!--            {{ $t('table.import') }}-->
          <!--          </el-button>-->
          <!--          <el-button v-waves v-permission="['metadata:source:export']" :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport">-->
          <!--            {{ $t('table.export') }}-->
          <!--          </el-button>-->
        </div>

        <el-table
          ref="table"
          :key="tableKey"
          v-loading="listLoading"
          element-loading-text="正在加载，请稍后"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <!--          <el-table-column type="selection" width="55" />-->
          <el-table-column type="index" align="center" width="50" label="序号" />
          <el-table-column align="center" label="拖拽" width="80">
            <template slot-scope="{}">
              <svg-icon class="drag-handler" icon-class="drag" />
            </template>
          </el-table-column>
          <el-table-column label="数据源名称" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数据源类型" min-width="150px" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.dbType | dictLabel('datasource_type') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="150px" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.status | dictLabel('is_use') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="元数据同步" min-width="150px" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.isSync | dictLabel('is_sync') }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="数据源连接信息" min-width="150px">
            <template slot-scope="{row}">
              <span>{{ row.dbSchema }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" fixed="right" align="center" min-width="230" class-name="small-padding fixed-width">
            <template slot-scope="{ row }">
              <el-button v-permission="['metadata:source:update']" type="text" size="small" icon="el-icon-edit" @click="handleUpdate(row)">
                {{ $t('table.edit') }}
              </el-button>
              <el-button v-permission="['metadata:source:update']" type="text" size="small" icon="el-icon-edit" @click="handleLook(row)">
                {{ $t('table.look') }}
              </el-button>
              <el-button v-permission="['metadata:source:sync']" type="text" size="small" icon="el-icon-edit" @click="handleSync(row)"> 元数据同步 </el-button>
              <el-button v-permission="['metadata:source:delete']" type="text" size="small" icon="el-icon-delete" class="delete-text-btn" @click="handleDelete(row, 'deleted')">
                {{ $t('table.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <import ref="import" template-url="/system/metadata/source/template" import-url="/system//metadata/source/import" @refreshList="getList" />
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" :page-sizes="pageArray" @pagination="getList" />

        <source-form ref="form" @refreshList="getList" />
      </div>
    </el-col>
    <treeData ref="treeForm" @getTreeList="getTreeList" />
  </el-row>
</template>

<script>
import { deletesource, fetchsourceList, exportsource, syncsource } from '@/api/metadata/source/source'
import { fetchMasterdataDirectoryList, createMasterdataDirectory, updateMasterdataDirectory, getMasterdataDirectory, deleteMasterdataDirectory } from '@/api/masterdata/masterdataDirectory'
import Import from '@/components/Import/import'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission/permission'
import sourceForm from './sourceForm'
import Pagination from '@/components/Pagination'
import Sortable from 'sortablejs'
import treeData from './treeData.vue'
export default {
  name: 'sourceList',
  components: { sourceForm, Pagination, Import, treeData },
  directives: { waves, permission },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      multipleSelection: [],
      downloadLoading: false,
      listLoading: true,
      pageArray: this.$store.getters.pageArray,
      listQuery: {
        sourceName: undefined,
        dbType: undefined,
        status: undefined,
        isSync: undefined,
        directoryId: '',
        page: 1,
        limit: this.$store.getters.defaultPageSize,
      },
      treeQuery: {
        tableName: undefined,
        page: 1,
        limit: this.$store.getters.defaultPageSize,
        ancestralId: '7',
      },
      treeList: [],
      NODE_KEY: 'id', // id对应字段
      MAX_LEVEL: 5, // 设定最大层级
      NODE_ID_START: 0, // 新增节点id，逐次递减
      startId: null,
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      initParam: {
        // 新增参数
        name: '新增节点',
        parentId: 0,
        children: [],
      },
      currentNodekey: '',
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
  },
  created() {
    // this.getList()
    this.getTreeList()
  },
  methods: {
    getTreeList() {
      this.listLoading = true
      fetchMasterdataDirectoryList(this.treeQuery).then((response) => {
        if (response.data.code == 200) {
          this.treeList = response.data.data
          if (this.treeList.length > 0) {
            this.listQuery.directoryId = this.treeList[0].children[0].id
            this.currentNodekey = this.treeList[0].id
            this.getList()
            this.$nextTick(() => {
              this.$refs.SlotTree.setCurrentKey(this.currentNodekey) //一定要加这个选中了否则样式没有出来
            })
          }
          this.listLoading = false
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    getList() {
      this.listLoading = true
      fetchsourceList(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        this.setSort()
        this.listLoading = false
      })
    },
    handleCreate() {
      if (this.listQuery.directoryId) {
        this.$refs.form.handleCreate(this.listQuery.directoryId)
      } else {
        this.$message.warning('请选择目录')
      }
    },
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row.id)
    },
    handleLook(row) {
      this.$refs.form.handleLook(row.id)
    },
    handleDelete(row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletesource(row.id).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSync(row) {
      syncsource(row.id).then((res) => {
        if (res.data.code === 0) {
          this.getList()
          this.$message.success(response.data.msg)
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletesource(this.ids).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleImport() {
      this.$refs.import.show()
    },
    handleExport() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.downloadLoading = true
      exportsource(this.ids).then((response) => {
        this.downloadLoading = true
        if (response.data.code === 0) {
          import('@/vendor/Export2Excel').then((excel) => {
            excel.export_byte_to_excel(response.data.data.bytes, response.data.data.title)
            this.downloadLoading = false
          })
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    setSort() {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        setData: function (dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: (evt) => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)
          // TODO：这里完成自己的业务处理
        },
      })
    },
    handleFilter() {
      if (this.listQuery.directoryId) {
        this.listQuery.page = 1
        this.getList()
      } else {
        this.$message.warning('请选择目录')
      }
    },
    handleNodeClick(data) {

      this.listQuery.directoryId = data.id
      //  this.directoryId=data.id
      this.getList()
    },
    handleDeletetree(_node, _data) {
      // 删除节点

      console.log(_node, _data)
      // 判断是否存在子节点
      if (_data.children && _data.children.length !== 0) {
        this.$message.error('此节点有子级，不可删除！')
        return false
      } else {
        // 删除操作
        let DeletOprate = () => {
          this.$nextTick(() => {
            if (this.$refs.SlotTree) {
              deleteMasterdataDirectory(_data.id).then((res) => {
                 
                this.$message.success('删除成功！')
                this.$refs.SlotTree.remove(_data)
              })
            }
          })
        }

        // 二次确认
        let ConfirmFun = () => {
          this.$confirm('是否删除此节点？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              DeletOprate()
            })
            .catch(() => {})
        }

        // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
        _data[this.NODE_KEY] < this.NODE_ID_START ? DeletOprate() : ConfirmFun()
      }
    },
    handleInput(_node, _data) {
      // 修改节点
      console.log(_node, _data)

      // updateMasterdataDirectory(obj).then(res=>{
      //   if(res.data.code==0){
      //     this.$message.success(res.data.msg)
      //     this.getTreeList()
      //   }else{
      //     this.$message.error(res.data.msg)
      //   }
      // })
      // 退出编辑状态
      if (_node.isEdit) {
        this.$set(_node, 'isEdit', false)
      }
    },
    handleLook(_node, _data) {
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description,
      }
      this.$refs.treeForm.handleLook(obj, this.treeQuery.ancestralId)
    },
    handleEdit(_node, _data) {
      // 编辑节点
      console.log(_node, _data)
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description,
      }
      this.$refs.treeForm.handleUpdate(obj, this.treeQuery.ancestralId)
      // // 设置编辑状态
      // if(!_node.isEdit){
      // 	this.$set(_node, 'isEdit', true)
      // }

      // // 输入框聚焦
      // this.$nextTick(() => {
      // 	if(this.$refs['slotTreeInput'+_data[this.NODE_KEY]]){
      // 		this.$refs['slotTreeInput'+_data[this.NODE_KEY]].$refs.input.focus()
      // 	}
      // })
    },
    handleAdd(_node, _data) {
      // 新增节点
      console.log(_node, _data)
      // // 判断层级
      if (_node.level >= this.MAX_LEVEL) {
        this.$message.warning('当前已达到' + this.MAX_LEVEL + '级，无法新增！')
        return false
      }
      // 参数修改
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = _data.id // 父id
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      this.$refs.treeForm.handleCreate(obj, this.treeQuery.ancestralId)
      // 判断字段是否存在
      // if(!_data.children){
      // 	this.$set(_data, 'children', [])
      // }
      // 展开节点
      // if(!_node.expanded){
      // 	_node.expanded = true
      // }
    },
    handleAddTop() {
      // 添加顶部节点
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = 0
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      // console.log(obj,'顶部参数')
      this.$refs.treeForm.handleCreate(obj, this.treeQuery.ancestralId)
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep(::-webkit-scrollbar) {
  display: block !important;
}
.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 90px;
  color: #99a9bf;
}
.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}
</style>
